<?php

namespace app\admin\controller;

use app\admin\model\bin\Type;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\admin\model\order\Rent as OrderRent;
use app\admin\model\bin\Rent;
use app\admin\model\bin\Sell as BinSell;
use app\admin\model\bin\Native;
use app\admin\model\Organization;

/**
 * 箱子
 *
 * @icon fa fa-circle-o
 */
class Bin extends Backend
{

    /**
     * Bin模型对象
     * @var \app\admin\model\Bin
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bin;
        $this->view->assign("currencyTypeList", $this->model->getCurrencyTypeList());
        $this->view->assign("currentStatusList", $this->model->getCurrentStatusList());
        $this->view->assign("lastStatusList", $this->model->getLastStatusList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams(null,true);
        $list = $this->model
            ->with([
                'type'=>function($query){$query->withField('name');},
                'native'=>function($query){$query->withField('name');},
                'bincompany'=>function($query){$query->withField('organ_name');},
                'ourcompany'=>function($query){$query->withField('organ_name');},
                'yard'=>function($query){$query->withField('organ_name');},
                'order'=>function($query){$query->withField('purchase_type,createtime,bin_native,bin_company_id,our_company_id');},
/*                'sellorder'=>function($query){$query->withField('take_null_time,take_number');},*/
            ])
            ->where($where)
            ->order(['current_status'=>'asc','createtime'=>'desc'])
            ->paginate($limit);
        $lists=$list->toArray();
        $data=$lists['data'];
        $OrderRent=new OrderRent();
        $BinSell=new BinSell();
        foreach ($data as &$v){
            $BinSellData= $BinSell->field('take_null_time,take_number')->where(['bin_id'=>$v['id']])->find();
            $v['binSell']['take_null_time']='';
            $v['binSell']['take_number']='';
            if(!empty($BinSellData)){
                $v['binSell']['take_null_time']=$BinSellData['take_null_time'];
                $v['binSell']['take_number']=$BinSellData['take_number'];
            }


            $v['firstentertime']=date('Y-m-d',$v['firstentertime']);
            $v['createtime']=date('Y-m-d',$v['createtime']);
            $v['updatetime']=date('Y-m-d',$v['updatetime']);
            $v['total_rent_time']=db('bin_rent')->where(['bin_id'=>$v['id']])->count();
            $binRentData  =db('bin_rent')->where(['bin_id'=>$v['id']])->order(['renttime'=>'desc','id'=>'desc'])->find();
            $v['last_rent_number']='';
            if(!empty($binRentData)){
                $v['last_rent_number']=$OrderRent->where(['id'=>$binRentData['rent_order_id']])->value('rent_sn');
            }
        }

        $result = array("total" => $lists['total'], "rows" => $data);


        return json($result);

    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /*
     * 租箱选择箱子
     */
 public function choose_bin(){
     $this->request->filter(['strip_tags','trim']);
     $params =$this->request->param();
     //如果发送的来源是Selectpage，则转发到Selectpage

     $real_where1=[];

     if(!empty($params['custom']['bin_type'])) {
         $real_where1['bin_type'] = $params['custom']['bin_type'];
     }

     if(!empty($params['custom']['bin_native'])){
         $real_where1['bin_native']=$params['custom']['bin_native'];
     }

     $bin_sn=$params['bin_sn'];
     if(!empty($bin_sn)){
         $real_where1['bin_sn']=['like',"%$bin_sn%"];
     }

     $list = $this->model
         ->field('id,bin_sn,origin_sn,yard_id,bin_origin,bin_native,bin_type,take_number,our_company_id,current_status')
         ->with([
             'type'=>function($query){$query->withField('name');},
             'native'=>function($query){$query->withField('name');},
         ])
         ->where($real_where1)
                  ->where(['bin_origin'=>$params['custom']['bin_origin'],'yard_id'=>$params['custom']['take_yard_id'],'current_status'=>1])
                  ->order(['bin.updatetime'=>'asc','bin.id'=>'asc'])
                  ->select();
     $json = json_encode((object)$list);
     $lists = json_decode($json, true);

     foreach ($lists as $k=> &$vo){
         $vo['bin_type_name']=$vo['type']['name'];
         $vo['bin_native_name']=$vo['native']['name'];
     }

     //数组根据当前页码和每页数据获取当前页的数据
     // 排序
     $page=$params['pageNumber'];
     $pageSize=$params['pageSize'];
     $start=($page-1)*$pageSize;
     $Data=array_slice($lists,$start,$pageSize);


     $result = ['total' => count($lists), 'list' => $Data];
     return json($result);

 }

       /*
        * 还箱选择箱子
        */
    public function restore_choose_bin(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage
        $where1=[];
        $bin_sn=$params['bin_sn'];
        if(!empty($bin_sn)){
            $where1['bin_sn']=['like',"%$bin_sn%"];
        }

        $rent=new Rent();
        $list = $rent
            ->field('id,bin_id,bin_sn,bin_type,bin_origin,bin_native,currency_type,deadlinetime,overdue_fee')
            ->with([
                'type'=>function($query){$query->withField('name');},
                'native'=>function($query){$query->withField('name');},
            ])
            ->where(['bin_origin'=>$params['custom']['bin_origin'],'customer_id'=>$params['custom']['customer_id'],'current_status'=>1])
            ->where($where1)
            ->order(['rent.renttime'=>'asc','rent.id'=>'asc'])
            ->select();
        $json = json_encode((object)$list);
        $lists = json_decode($json, true);

        foreach ($lists as $k=> &$vo){
            $vo['bin_type_name']=$vo['type']['name'];
            $vo['bin_native_name']=$vo['native']['name'];
        }

        //数组根据当前页码和每页数据获取当前页的数据
        // 排序
        $page=$params['pageNumber'];
        $pageSize=$params['pageSize'];
        $start=($page-1)*$pageSize;
        $Data=array_slice($lists,$start,$pageSize);


        $result = ['total' => count($lists), 'list' => $Data];
        return json($result);

    }

    /*
       * 还箱选择箱子
       */
    public function withdraw_choose_bin(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage

        $organization=new Organization();
        $real_where1=[];
        $where1=[];

        if(!empty($params['custom']['bin_origin'])){
            $real_where1['bin_origin']=$params['custom']['bin_origin'];
            $real_where1['current_status']=1;
        }

        $bin_sn=$params['bin_sn'];
        if(!empty($bin_sn)){
            $real_where1['bin_sn']=['like',"%$bin_sn%"];
        }

        $bin_company_id=$params['custom']['bin_company_id'];
        $page=$params['pageNumber'];
        $pageSize=$params['pageSize'];

        //这个分页的数据
        $organizationData = $organization
            ->field('id,organ_name')
            ->with([
                'bcompanybin'=>function($query)use($real_where1){$query->where($real_where1);},
            ])
            ->find($bin_company_id)
            ->toArray();

        $binList=$organizationData['bcompanybin'];

        foreach ($binList as $k=> &$vo){
            $vo['bin_type_name']=Type::where(['id'=>$vo['bin_type']])->value('name');
            $vo['bin_native_name']=Native::where(['id'=>$vo['bin_native']])->value('name');
        }

        $start=($page-1)*$pageSize;
        $Data=array_slice($binList,$start,$pageSize);


        $result = ['total' => count($binList), 'list' => $Data];
        return json($result);
    }

    /*
   * 调拨选择箱子
   */
    public function allot_choose_bin(){
        $this->request->filter(['strip_tags','trim']);
        $params =$this->request->param();
        //如果发送的来源是Selectpage，则转发到Selectpage

        $list = $this->model
            ->field('id,bin_sn,origin_sn,yard_id,bin_origin,bin_native,take_number,our_company_id,current_status')
            ->with([
                'type'=>function($query){$query->withField('name');},
                'native'=>function($query){$query->withField('name');},
            ])
            ->where(['bin_type'=>$params['custom']['bin_type'],'yard_id'=>$params['custom']['take_yard_id'],'current_status'=>1])
            ->order(['bin.updatetime'=>'asc','bin.id'=>'asc'])
            ->select();
        $json = json_encode((object)$list);
        $lists = json_decode($json, true);

        foreach ($lists as $k=> &$vo){
            $vo['bin_type_name']=$vo['type']['name'];
            $vo['bin_native_name']=$vo['native']['name'];
        }

        //数组根据当前页码和每页数据获取当前页的数据
        // 排序
        $page=$params['pageNumber'];
        $pageSize=$params['pageSize'];
        $start=($page-1)*$pageSize;
        $Data=array_slice($lists,$start,$pageSize);


        $result = ['total' => count($lists), 'list' => $Data];
        return json($result);

    }
    }
